﻿using Okra.Navigation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Contacts;
using Windows.ApplicationModel.Contacts.Provider;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace Dynamics.NAV.Metro.Pages.ContactPicker
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split Application this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class ContactPickerPage : Dynamics.NAV.Metro.Common.LayoutAwarePage
    {
        CoreDispatcher dispatcher = Window.Current.Dispatcher;
        
        public ContactPickerPage()
        {
            this.InitializeComponent();
        }

        void AppendValue(Contact contact, string value, ContactFieldType type, ContactFieldCategory category)
        {
            if (!string.IsNullOrEmpty(value))
            {
                contact.Fields.Add(new ContactField(value, type, category));
            }
        }

        void AddCustomer(Data.NavCustomer customer)
        {
            Contact contact = new Contact();
            contact.Name = customer.Name;

            AppendValue(contact, customer.Email, ContactFieldType.Email, ContactFieldCategory.Work);

            AppendValue(contact, customer.PhoneNo, ContactFieldType.PhoneNumber, ContactFieldCategory.Work);

            if (!string.IsNullOrEmpty(customer.Address))
            {
                contact.Fields.Add(new ContactLocationField(customer.Address, ContactFieldCategory.None,
                    customer.Address2, customer.City, customer.State, customer.CountryCode, customer.ZipCode));
            }

            switch (((ContactPickerViewModel)DataContext).ContactPicker.AddContact(customer.No, contact))
            {
                case AddContactResult.Added:
                    // Notify the user that the contact was added
                    break;
                case AddContactResult.AlreadyAdded:
                    // Notify the user that the contact is already added
                    break;
                case AddContactResult.Unavailable:
                default:
                    // Notify the user that the basket is unavailable
                    break;
            }
        }

        async void contactPickerUI_ContactRemoved(ContactPickerUI sender, ContactRemovedEventArgs args)
        {
            // The event handler may be invoked on a background thread, so use the Dispatcher to run the UI-related code on the UI thread.
            string removedId = args.Id;
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                foreach (Data.NavCustomer customer in itemGridView.SelectedItems)
                {
                    if (customer.No == removedId)
                    {
                        itemGridView.SelectedItems.Remove(customer);
                        break;
                    }
                }
            });
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ((ContactPickerViewModel)DataContext).ContactPicker.ContactRemoved += contactPickerUI_ContactRemoved;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            ((ContactPickerViewModel)DataContext).ContactPicker.ContactRemoved -= contactPickerUI_ContactRemoved;
        }

        private void itemGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (Data.NavCustomer added in e.AddedItems)
            {
                AddCustomer(added);
            }

            foreach (Data.NavCustomer removed in e.RemovedItems)
            {
                if (((ContactPickerViewModel)this.DataContext).ContactPicker.ContainsContact(removed.No))
                {
                    ((ContactPickerViewModel)this.DataContext).ContactPicker.RemoveContact(removed.No);
                }
            }
        }
    }
}
